package com.ias.agdis_r.fragment.main;

import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentPagerAdapter;
//import android.support.v4.view.ViewPager;
import androidx.viewpager.widget.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseFragment;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.fragment.task.FTaskListFragment;
import com.ias.agdis_r.fragment.task.NFTaskListFragment;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.view.BadgeView;
import com.ias.agdis_r.view.control.MutipleTouchViewPager;

import java.util.ArrayList;
import java.util.List;

public class Task extends BaseFragment implements
        View.OnClickListener {
    private MutipleTouchViewPager mViewPager;
    private View view;
    /**
     * 三个Fragment
     */
    private FTaskListFragment fragmentFTask;
    private NFTaskListFragment fragmentNFTask;
    /**
     * 顶部的三个TextView
     */
    private TextView txt_ftask_label;
    private TextView txt_nftask_label;
    /**
     * 顶部三个LinearLayout
     */
    private LinearLayout layout_ftask_tab;
    private LinearLayout layout_nftask_tab;

    /**
     * 分别为每个TabIndicator创建一个BadgeView
     */
    private BadgeView mBadgeViewforFTask;
    private BadgeView mBadgeViewforNFTask;
    /**
     *
     */
    private LinearLayout layout_task_type;
    /**
     * Tab的那个引导线
     */
    private ImageView mTabLine;
    /**
     * ViewPager的当前选中页
     */
    private int currentIndex = JavaBeanManager.getInstance().getUserinfo()
            .getTaskCurrentIndex();
    /**
     * 屏幕的宽度
     */
    private int screenWidth;

    private int ftaskCount;
    private int nftaskCount;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub
        if (serviceId.equals(MessageModel.TRPT)) {
            if(fragmentFTask!=null) {
                fragmentFTask.updateUI(serviceId);
            }
            if(fragmentNFTask!=null){
                fragmentNFTask.updateUI(serviceId);
            }
            //更新角标数量
            updateBadge();
        }
    }

    @Override
    protected void updateUI(String tag) {
        // TODO Auto-generated method stub
        // 接收刷新信息，刷新页面
        if (tag.equals(MessageModel.ITSD) || tag.equals(MessageModel.TTSD)
                || tag.equals(MessageModel.REFRESH)) {
            if(fragmentFTask!=null) {
                fragmentFTask.updateUI(tag);
            }
            if(fragmentNFTask!=null){
                fragmentNFTask.updateUI(tag);
            }
            //更新角标数量
            updateBadge();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.task_main, container, false);
        mViewPager = (MutipleTouchViewPager) view.findViewById(R.id.id_viewpager);
        layout_task_type = (LinearLayout)view.findViewById(R.id.layout_task_type);
        initView();
        initTabLine(currentIndex);
        setListener();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_EVENTTASK.toString())) {
            layout_task_type.setVisibility(View.GONE);
            mViewPager.setNoScroll(true);
            mViewPager.setCurrentItem(0);
        } else {
            layout_task_type.setVisibility(View.VISIBLE);
            mViewPager.setNoScroll(false);
        }
    }

    private void setListener(){
        /**
         * 设置监听
         */
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 重置所有TextView的字体颜色
                resetTextView();
                switch (position) {
                    case 0:
                        mBadgeViewforFTask.setBadgeCount(ftaskCount);
                        txt_ftask_label.setTextColor(getResources().getColor(R.color.green));
                        break;
                    case 1:
                        mBadgeViewforNFTask.setBadgeCount(nftaskCount);
                        txt_nftask_label.setTextColor(getResources().getColor(R.color.green));
                        break;
                }
                currentIndex = position;
                UserInfoBean userInfo = JavaBeanManager.getInstance().getUserinfo();
                if (userInfo != null) {
                    JavaBeanManager.getInstance().getUserinfo().setTaskCurrentIndex(currentIndex);
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                /**
                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
                 */
                if (currentIndex == 0 && position == 0)// 0->1
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (positionOffset
                            * (screenWidth * 1.0 / 2) + currentIndex
                            * (screenWidth / 2));
                    mTabLine.setLayoutParams(lp);

                } else if (currentIndex == 1 && position == 0) // 1->0
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (-(1 - positionOffset)
                            * (screenWidth * 1.0 / 2) + currentIndex
                            * (screenWidth / 2));
                    mTabLine.setLayoutParams(lp);
                } else if (currentIndex == 1 && position == 1) // 1->2
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (positionOffset
                            * (screenWidth * 1.0 / 2) + currentIndex
                            * (screenWidth / 2));
                    mTabLine.setLayoutParams(lp);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        if (currentIndex == -1) {
            mViewPager.setCurrentItem(0);
            txt_ftask_label.setTextColor(getResources().getColor(R.color.green));
        }
        else {
            // 当currentIndex为0时启动activity不执行onPageSelected
            if (currentIndex == 0) {
                txt_ftask_label.setTextColor(getResources().getColor(R.color.green));
            }
            mViewPager.setCurrentItem(currentIndex);
        }

    }

    /**
     * 初始化控件，初始化Fragment
     */
    private void initView() {
        layout_ftask_tab = (LinearLayout) view.findViewById(R.id.id_tab_ftask);
        layout_nftask_tab = (LinearLayout) view.findViewById(R.id.id_tab_nftask);

        layout_ftask_tab.setOnClickListener(this);
        layout_nftask_tab.setOnClickListener(this);

        txt_ftask_label = (TextView) view.findViewById(R.id.id_ftask);
        txt_nftask_label = (TextView) view.findViewById(R.id.id_nftask);

        fragmentFTask = new FTaskListFragment();
        fragmentNFTask = new NFTaskListFragment();
        mFragments.add(fragmentFTask);
        mFragments.add(fragmentNFTask);

        mBadgeViewforFTask = new BadgeView(getActivity());
        mBadgeViewforNFTask = new BadgeView(getActivity());

        mAdapter = new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };
        ftaskCount = DataManager.getInstance().getReceiveTaskNum();
        nftaskCount = DataManager.getInstance().getNFReceiveTaskNum();
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(1);
        mBadgeViewforFTask.setBadgeCount(ftaskCount);
        layout_ftask_tab.addView(mBadgeViewforFTask);

        mBadgeViewforNFTask.setBadgeCount(nftaskCount);
        layout_nftask_tab.addView(mBadgeViewforNFTask);
    }

    /**
     * 根据屏幕的宽度，初始化引导线的宽度
     *
     * @param page
     */
    private void initTabLine(int page) {
        mTabLine = (ImageView) view.findViewById(R.id.id_tab_line);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getActivity().getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(outMetrics);
        screenWidth = outMetrics.widthPixels;
        LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                .getLayoutParams();
        lp.width = screenWidth / 2;
        if (page != -1) {
            lp.leftMargin = (int) (screenWidth * 1.0 / 2) * page;
            mTabLine.setLayoutParams(lp);
        } else {
            mTabLine.setLayoutParams(lp);
        }
    }

    /**
     * 重置颜色
     */
    protected void resetTextView() {
        txt_ftask_label.setTextColor(getResources().getColor(R.color.black));
        txt_nftask_label.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_tab_ftask:
                mViewPager.setCurrentItem(0);
                break;
            case R.id.id_tab_nftask:
                mViewPager.setCurrentItem(1);
                break;
        }
    }

    //设置任务移交多选模式
    public void setMultiselect(boolean flag_multiselect){

        if(fragmentFTask!=null) {
            fragmentFTask.setMultiselect(flag_multiselect);
        }
    }

    //设置任务转发单选模式
    public void setSinglchoice(boolean flag_singlchoice){

        if(fragmentFTask!=null) {
            fragmentFTask.setSinglchoice(flag_singlchoice);
        }
    }

    /**
     * 增加排序功能
     *
     * @param sortType
     */
    public void sort(int sortType) {
        if(fragmentFTask!=null) {
            fragmentFTask.sort(sortType);
        }
        if(fragmentNFTask!=null){
            fragmentNFTask.sort(sortType);
        }
        //更新角标数量
        updateBadge();
    }

    private void updateBadge(){
        ftaskCount = DataManager.getInstance().getReceiveTaskNum();
        nftaskCount = DataManager.getInstance().getNFReceiveTaskNum();
        if(mBadgeViewforFTask!=null) {
            mBadgeViewforFTask.setBadgeCount(ftaskCount);
        }
        if(mBadgeViewforNFTask!=null) {
            mBadgeViewforNFTask.setBadgeCount(nftaskCount);
        }
    }
}
